﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace linkouqs.Gamekit {
    public class Slot : MonoBehaviour, IPointerEnterHandler, IPointerDownHandler,IPointerExitHandler
    {
        public GameObject itemPrefab;

        public Color enterColor;
        public bool isSelected = false;

        public virtual void StoreItem(Item item)
        {
            if(transform.childCount==0||transform.GetChild(0).name=="Price")
            {
                GameObject itemGameObject = Instantiate(itemPrefab) as GameObject;
                itemGameObject.transform.SetParent(this.transform);
                itemGameObject.transform.localScale = Vector3.one;
                itemGameObject.transform.localPosition = Vector3.zero;
                
                itemGameObject.GetComponent<ItemUI>().SetItem(item);
            }
            else
            {
                
                transform.GetChild(0).GetComponent<ItemUI>().AddAmount();
            }
        }

        public ItemType GetItemType()
        {
            return transform.GetChild(0).GetComponent<ItemUI>().Item.ItemType;
          
        }

        public int GetItemId()
        {
          
           return transform.GetComponentInChildren<ItemUI>().Item.ID;
             
        }

        public bool IsFilled()
        {
            ItemUI itemUI = transform.GetChild(0).GetComponent<ItemUI>();
            return itemUI.Amount >= itemUI.Item.Capacity;
          
        }


        public void OnPointerDown(PointerEventData eventData)
        {
           

            if (eventData.button != PointerEventData.InputButton.Left) return;

            if(transform.childCount>0)
            {
                if (InventoryManager.Instance.selectSlot != null)
                {
                    
                    InventoryManager.Instance.selectSlot.GetComponent<Image>().color = Color.white;
                    InventoryManager.Instance.selectSlot = null;
                }
                ItemUI currentItem = transform.GetComponentInChildren<ItemUI>();          
                InventoryManager.Instance.PickupItemUI(currentItem, this);
            }
            else
            {
                Debug.LogWarning("该物品槽没有物品");
            }

        }

        public void OnPointerEnter(PointerEventData eventData)
        {
            this.GetComponent<Image>().color = enterColor;
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            if (InventoryManager.Instance.selectSlot==this) return;
            this.GetComponent<Image>().color = Color.white;
        }
    }
}
